

import 'package:dio/dio.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:syria_sports/data/apiClient/api_keys.dart';
import 'package:flutter/foundation.dart';

import '../../core/utils/show_toast.dart';


class ErrorModel{
  String? message;
  final String stacktrace;
  final int? stateCode;
  final bool? state;
  final dynamic from;

  ErrorModel({required this.stacktrace,  this.message ,this.stateCode , this.from ,this.state}){
    if(kDebugMode) {
      print('error: $message state code:${stateCode??'none'} from:${from.runtimeType}');
    }
    message ??= 'msg_something_went_wrong'.tr;

  }

  static ErrorModel fromResponse(Response response){

    if(response.data is! Map){
      print('respinse type not valid\n${response.data}');
      showMessage('msg_something_went_wrong'.tr);
      return ErrorModel(stacktrace: response.data , stateCode: response.statusCode, from: response.realUri.path,state: response.data['state']);
    }

    try {
      print("error message: ${response.data[ApiKeys.message]}\nstate code:${response.statusCode}");
    } catch (e) {
      print('cathe error in server \n$e');
    }

    if(response.statusCode == 401){
      if(PrefUtils.isLogged()) {
        showUnauthenticatedDialog();
      }
      PrefUtils.clearPreferencesData();
    }else if(response.statusCode == 402){
      showAccountDisabledDialog();
    }else {
      try {
        showMessage(response.data[ApiKeys.message]);
      } catch (e) {
        showMessage('msg_something_went_wrong'.tr);
      }

    }

    return ErrorModel(
      stacktrace: response.data[ApiKeys.message],
      stateCode: response.statusCode,
      from: response.realUri.path,
      state: response.data['state'],
    );
  }


  static ErrorModel fromException (dynamic  e){
    return ErrorModel(stacktrace: '' ,message: e.toString());
  }

}